import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * jedis 操作 redis hash基本命令
 */

public class RedisDemoHash {
    public static void test1(Jedis jedis) {
        System.out.println("hset 和 hget");
        jedis.flushDB();

        jedis.hset("key", "f1", "v1");
        Map<String , String > map = new HashMap<>();
        map.put("f2", "f2");
        map.put("f3", "f3");
        map.put("f4", "f4");
        map.put("f5", "f5");
        jedis.hset("key",map);
        String result = jedis.hget("key", "f6");
        System.out.println("result: " + result);
    }
    public static void test2(Jedis jedis) {
        System.out.println("hexists 和 hdel");
        jedis.flushDB();

        jedis.hset("key", "f1", "v1");
        String result = jedis.hget("key", "f1");
        System.out.println("result: " + result);
        jedis.hdel("key", "f1");
        result = jedis.hget("key", "f1");
        System.out.println("result: " + result);
    }
    public static void test3(Jedis jedis) {
        System.out.println("hkeys 和 hvals");
        jedis.flushDB();

        Map<String, String> map = new HashMap<>();
        map.put("f1","v1");
        map.put("f2","v2");
        map.put("f3","v3");
        map.put("f4","v4");
        map.put("f5","v5");
        jedis.hset("key",map);
        Set<String> hkeys = jedis.hkeys("key");
        System.out.println("hkeys: " + hkeys);
        List<String> hvals = jedis.hvals("key");
        System.out.println("hvals: " + hvals);
    }
    public static void test4(Jedis jedis) {
        System.out.println("hmget 和 hmset");
        jedis.flushDB();
        Map<String, String> map = new HashMap<>();
        map.put("f1","v1");
        map.put("f2","v2");
        map.put("f3","v3");
        map.put("f4","v4");
        map.put("f5","v5");
        jedis.hmset("key", map);
        List<String> result = jedis.hmget("key", "f1", "f2", "f100", "f3");
        System.out.println("result: " + result);
    }
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");

        try(Jedis jedis = jedisPool.getResource()) {
            // test1(jedis);
            // test2(jedis);
            // test3(jedis);
            test4(jedis);
        }
    }
}
